package com.example.shipload_e.update_tool;

import java.io.File;

import org.apache.http.Header;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.example.shipload_e.huawei_push.MyApplication;
import com.example.shipload_e.util.HttpConstant;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.FileAsyncHttpResponseHandler;

public class UpdateBiz {

	public void downloadApk(final Handler handler,final String path,final String apkUrl,
	        final Context context,final File file) {

		MyApplication.asyncHttpClient.get(apkUrl, new FileAsyncHttpResponseHandler(file) {
			@Override
			public void onProgress(int bytesWritten,int totalSize) {
				// TODO Auto-generated method stub
				super.onProgress(bytesWritten, totalSize);

				int progress = (int) (((float) bytesWritten / totalSize) * 100);
				// context.updateProgress(progress);

			}

			@Override
			public void onSuccess(int arg0,Header[] arg1,File file) {
				// TODO Auto-generated method stub
				Log.i("SSS", "zaizeh");

				try {
					Message message = handler.obtainMessage();
					Bundle bundle = new Bundle();
					message.what = HttpConstant.DOWN_APK_SUCCEE;

					bundle.putString(HttpConstant.KEY_DATA, path);
					message.setData(bundle);
					handler.sendMessage(message);

				} catch (Exception e) {
					// TODO: handle exception
				}
			}

			@Override
			public void onFailure(int arg0,Header[] arg1,Throwable arg2,File arg3) {
				// TODO Auto-generated method stub
				NetworkUtil.checkNetworkState(context);
			}
		});
	}

	public void getVersionInfo(final Handler handler,final Context context) {
		String jsonUrl = "http://56cyt.com:8088/shiploade_update_tool/servlet/ApkUpdateServlet";// 客户APP
		// 船舶app
		MyApplication.asyncHttpClient.get(jsonUrl, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(int statusCode,Header[] headers,byte[] responseBody) {

				String jsonString = null;
				VersionEntity versionInfo = null;
				try {
					jsonString = new String(responseBody);

					jsonString = jsonString.substring(2);
					Log.i("SSS", jsonString);
					versionInfo = UpdateParser.parser(jsonString);
				} finally {
					Message message = handler.obtainMessage();
					message.what = HttpConstant.GET_VERSION_SUCCEE;
					Bundle bundle = new Bundle();
					bundle.putSerializable(HttpConstant.KEY_VERSION_DATA, versionInfo);
					message.setData(bundle);
					handler.sendMessage(message);
				}

			}

			@Override
			public void onFailure(int statusCode,Header[] headers,byte[] responseBody,
			        Throwable error) {

			}
		});
	}
}
